﻿using System.Drawing;
using System.Windows.Forms;

namespace Boxman {
    // 箱子
    class Box: BaseGameObject {
        private BaseGameObject mBack;   // 背后对象
        protected Image mCurrentImage;  // 当前图片
        protected Image mImage2;        // 图片2

        /**
         * 构造方法。
         * @param back      背后对象
         * @param drawer    绘图者
         * @param type      类型
         * @param x, y      左上角坐标
         */
        public Box(BaseGameObject back, Graphics drawer, Type type, int x, int y): 
            base(drawer, type, x, y) {
            // 初始化成员
            mBack = back;
            mCurrentImage = mImage;
            string imageFilePath = string.Format(Const.IMAGE_FILE_PATH, (int)type * 10 + 1);
            mImage2 = Image.FromFile(imageFilePath);
        }

        /**
         * 移动。
         * @param direction     方向
         * @param moveResult    移动结果
         * @return 被推动的箱子
         */
        public override BaseGameObject Move(Keys direction, ref MoveResult moveResult) {
            bool leftFromDest = false;  // 是否离开目的地
            int destX = mX, destY = mY; // 新位置的坐标

            // 计算新位置
            if (direction == Keys.Left) {
                destX--;
            } else if (direction == Keys.Right) {
                destX++;
            } else if (direction == Keys.Up) {
                destY--;
            } else if (direction == Keys.Down) {
                destY++;
            }

            // 如果旁边是墙或箱子，则直接返回
            if (Game.sBaseGameObjects[destY, destX]._Type == Type.WALL ||
                Game.sBaseGameObjects[destY, destX]._Type == Type.BOX) {
                moveResult = MoveResult.NO_MOVE;
                return null;
            }

            // 设置移动结果
            if (moveResult < MoveResult.NORMAL_MOVED) {
                moveResult = MoveResult.NORMAL_MOVED;
            }

            // 判断是否要离开目的地
            if (_Type == Type.BOX && mBack._Type == Type.DESTINATION) {
                leftFromDest = true;
                moveResult = MoveResult.LEFT_FROM_DEST;
                mCurrentImage = mImage;
            }

            // 用背后对象擦除自己
            mBack.Draw();
            Game.sBaseGameObjects[mY, mX] = mBack;

            // 计算新位置
            mX = destX;
            mY = destY;

            // 设置新的背后对象
            mBack = Game.sBaseGameObjects[mY, mX];

            // 判断是否到达目的地
            if (_Type == Type.BOX && mBack._Type == Type.DESTINATION) {
                if (leftFromDest) {
                    moveResult = MoveResult.NORMAL_MOVED;
                } else {
                    moveResult = MoveResult.ARRIVED_ON_DEST;
                }
                mCurrentImage = mImage2;
            }

            // 重绘自己
            mDrawer.DrawImage(mCurrentImage, mX * Const.GRID_SIZE, mY * Const.GRID_SIZE, Const.GRID_SIZE, Const.GRID_SIZE);

            // 将自己保存到数组中
            Game.sBaseGameObjects[mY, mX] = this;

            return this;
        }
    }
}
